package com.example.repair.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.repair.R;
import com.example.repair.base.BaseActivity;
import com.example.repair.base.Presenter.PressenterImpl;
import com.example.repair.base.netWork.Constant;
import com.example.repair.base.netWork.LoginContract;
import com.example.repair.entity.Bean;
import com.example.repair.entity.GetUserInfo;
import com.example.repair.util.BitmapUtil;
import com.example.repair.util.HeaderImageCallback;
import com.example.repair.util.SpUtils;
import com.example.repair.util.StringUtils;
import com.example.repair.util.TakePhotoUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MyinfoActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.headImage)
    SimpleDraweeView headImage;
    @BindView(R.id.nick)
    EditText nick;
    @BindView(R.id.edit_phone)
    EditText editPhone;

    private String uid;

    private List<String> sexlist = new ArrayList<>();
    private OptionsPickerView pvOptions;
    private String url;

    private PressenterImpl pressenter;

    @Override
    protected int getLayout() {
        return R.layout.activity_myinfo;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        sexlist.clear();
        sexlist.add("拍照");
        sexlist.add("相册");
        uid = SpUtils.getString(this, "uid");
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

    }

    @Override
    protected void initData() {

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid", uid);

        pressenter.sendMessage(this, Constant.get_userinfo, map, GetUserInfo.class);

    }

    @OnClick({R.id.back, R.id.image, R.id.sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.image:

                //选择地址
                pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        if (options1 == 0) {
                            //拍照
                            takePhotoClick();

                        } else {
                            //相册

                            // 检查读取和写入动态权限
                            if (ActivityCompat.checkSelfPermission(MyinfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                                choose_photo_layout_click();
                            } else {
                                // 如果没有，获取读取和写入动态权限
                                ActivityCompat.requestPermissions(MyinfoActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
                            }


                        }
                    }
                }).build();
                //三级选择器
                pvOptions.setPicker(sexlist);
                pvOptions.show();

                break;
            case R.id.sure:

                uploadImage();
                break;
        }
    }


    private static final int TAKE_PICTURE = 0;
    private static final int IMAGE = 1;
    private static final int REQUEST_CODE_ASK_PERMISSIONS = 2;


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                } else {
                    // 没有打开相机的权限
                    Toast.makeText(this, "没有打开照相机权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case 100:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    choose_photo_layout_click();
                } else {
                    // 没有打开相机的权限
                    Toast.makeText(this, "没有打开读取机权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 拍照
     */
    void takePhotoClick() {
        if (Build.VERSION.SDK_INT >= 23) {
//            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
            ActivityCompat.requestPermissions(MyinfoActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
        } else {
            startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
        }
    }

    /**
     * 选取相册图片
     */
    void choose_photo_layout_click() {
        //调用相册
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK && null != data) {
            String sdState = Environment.getExternalStorageState();
            if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                return;
            }
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            Bundle bundle = data.getExtras();
            //获取相机返回的数据，并转换为图片格式
            Bitmap bitmap = (Bitmap) bundle.get("data");
            FileOutputStream fout = null;
            File file = new File("/sdcard/pics/");
            file.mkdirs();
            String filename = file.getPath() + name;
            try {
                fout = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);
                showImage(filename);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    fout.flush();
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //显示图片
        } else if ((requestCode == IMAGE) && (resultCode == Activity.RESULT_OK) && (data != null)) {
            //获取图片路径
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            showImage(imagePath);
            c.close();
        }
    }

    //加载图片
    private void showImage(String imaePath) {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        url = TakePhotoUtil.saveTodisk(bm, Constant.HeadPath);
        headImage.setImageBitmap(bm);
    }

    private void uploadImage() {

        String nickName = nick.getText().toString();
        String phone = editPhone.getText().toString();


        if (nickName == null || nickName.equals("") || phone == null || phone.equals("")){
            Toast.makeText(this, "请检查数据", Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtils.isRegistMobileNO(phone)) {
            Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
            return;
        }

        PostFormBuilder postFormBuilder = OkHttpUtils.post().url(Constant.PATH + Constant.update_info)
                .addParams("uid", uid)
                .addParams("user_nickname", nickName)
                .addParams("mobile", phone)
                .addParams("address", SpUtils.getString(MyinfoActivity.this, "location"))
                .addParams("token", Constant.TOKEN);

        if (url != null && !url.equals("")) {

            postFormBuilder.addFile("image", url, new File(bitmapToString(BitmapUtil.getimage(url))));
        }

        postFormBuilder.build().execute(new HeaderImageCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(Bean response, int id) {
                Toast.makeText(MyinfoActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
                if (response != null && response.getCode() == 1) {
                    finish();
                }
            }
        });
    }

    public String bitmapToString(Bitmap bitmap) {
        //将bitmap转换为uri
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfo) {
            GetUserInfo getUserInfo = (GetUserInfo) data;

            headImage.setImageURI(Constant.PATH + getUserInfo.getData().getHeadsmall());
            nick.setText(getUserInfo.getData().getUser_nickname());
            editPhone.setText(getUserInfo.getData().getMobile());

        }
    }

    @Override
    public void fail(String error) {

    }
}
